<template>
  <div>
    <article class="innerPage bookList" v-loading="isloadingUploadLoccal">
      <header class="breadcrumb">
        <x-breadcrumb :path="$route.path" :title="$route.meta.breadcrumb" :startIndex="$route.meta.startIndex">
        </x-breadcrumb>
      </header>

      <div class="block">
        <div class="tip">温馨提示：请先上传文件，上传完成后，点击保存版权信息</div>
        <div class="row">

          <div class="type">类型</div>
          <el-select v-model="type_id" placeholder="请选择类型">
            <el-option v-for="item in typeList" :key="item.id" :label="item.type_name" :value="item.id">
            </el-option>
          </el-select>

          <div class="label" style="margin-left:20px">版权信息</div>
          <el-radio-group v-model="is_forever">
            <div class="groupRadio">
              <el-radio :label="0">非永久</el-radio>
              <el-radio :label="1">永久</el-radio>
            </div>
          </el-radio-group>

          <div class="time">
            版权截止时间
          </div>
          <el-date-picker class="picker-tiem" size="mini" v-model="copyright_end_time" type="datetime" :placeholder="'请选择版权截止时间'" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </div>
      </div>

      <div class="form" v-if="multipleUrl.length > 0">
        <el-upload class="upload-demo" drag :action="$upUrl" :on-change="multipleImg" :show-file-list="false" :auto-upload="false" accept=".epub" multiple>
          <div @click.stop="" class="upimg-maxbox">
            <div v-for="(item, index) in multipleUrl" :key="index" class="item">
              <div class="avatar">
                <div class="name">{{ item.file.name }}</div>
              </div>
              <div class="right">
                <p class="err-p" v-show="item.isSuccess == 2" style="color:#f56c6c">上传失败</p>
                <p class="suss-p" v-show="item.isSuccess == 1" style="color:#67c23a">上传成功</p>
                <div v-if="item.isSuccess !== 1">
                  <div>
                    <i class="el-icon-delete color" @click.stop="multipleRemove(index)"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-upload>
        <div class="caozuo-box">
          <div>
            <div v-if="isPercentage" class="progressMax">
              <el-progress :text-inside="true" :stroke-width="15" :percentage="percentageNum" class="progress-box"></el-progress>
              <span class="urldata-box">共{{ multipleUrl.length }}个，已上传{{
                    fromData.content.length
                  }}个，失败{{ errorImg.length }}个
              </span>
            </div>
            <p v-else class="urldata-box">
              选中{{ multipleUrl.length }}个文件
            </p>
          </div>
          <div>
            <div class="shang-box" v-if="isUpload">
              <el-upload class="avatar-uploader" name="production" ref="upload" :action="$upUrl" :show-file-list="false" :auto-upload="false" :on-change="changimg" accept=".epub" multiple>
                <el-button class="btn_addBox">继续添加</el-button>
              </el-upload>
              <el-button class="btn_shangchuan" @click="uploadBtn">
                开始上传
              </el-button>
            </div>
            <div class="shang-box" v-if="errorImg.length > 0">
              <el-button class="btn_shangchuan" @click="newuploadBtn">
                重新上传
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="form" v-else>
        <el-upload class="upload-boxTwo" drag :on-preview="beforeUpload" :on-success="beforeUpload" :on-progress="beforeUpload" :before-upload="beforeUpload" :action="$upUrl" :on-change="multipleImg" :show-file-list="false" :auto-upload="false" multiple accept=".epub">

          <div class="center">
            <img src="@/assets/img/file.png" alt="">
            <div class="btn">点击选择电子书文件</div>
            <div class="tip">或将电子书文件拖到这里，单次最多可选500个（文件格式.epub）</div>
          </div>

        </el-upload>
        <div class="img_ps">支持epub文件，大小控制在100M以内。</div>
      </div>
    </article>
  </div>
</template>

<script>
import { Loading } from 'element-ui';
export default {
  components: {},
  data() {
    return {
      copyright_end_time: '',
      is_forever: 1,
      type_id: undefined,
      remarkVisible: false,
      act_id: '',
      pictureArr: [],
      uploadLimit: 500,

      fromData: {
        user_id: '',
        content: []
      },
      multipleUrl: [],
      titles: '',
      percentageNum: 0,
      isPercentage: false,
      errorImg: [],
      isUpload: true,
      is_appoint: '',
      isloadingUploadLoccal: false,
      timer: undefined,
      typeList: []
    }
  },
  watch: {
    multipleUrl(val) {
      if (val.length == 0) {
        this.fromData.content = []
      }
    },
    'fromData.user_id'(val) {
      this.pictureArr = []
    }
  },
  mounted() {
    this.getTypeList()
  },
  activated() {
    // 进页面重置数据
    this.multipleUrl = []
    this.percentageNum = 0
    this.errorImg = []
    this.fromData = {
      user_id: '',
      content: []
    }
    this.pictureArr = []
    this.isPercentage = false
    this.isUpload = true
    this.act_id = this.$route.query.act_id
    this.is_appoint = this.$route.query.is_appoint
  },
  methods: {
    // 类型列表
    getTypeList() {
      this.request({ url: 'admin/resourceTotalType/filterList' }).then(res => {
        this.typeList = res.content
      }).catch(e => this.errorHandler(e))
    },
    // 批量上传图
    multipleImg(file) {
      const isLt100M = file.size / 1024 / 1024 <= 100
      if (!isLt100M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      } else {
        let multipleObj = {
          raw: URL.createObjectURL(file.raw),
          uid: file.uid,
          file: file.raw,
          isSuccess: undefined
        }

        this.multipleUrl.push(multipleObj)
        console.log(this.multipleUrl);
      }
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.isloadingUploadLoccal.close()
      }, 1000)
    },
    beforeUpload() {
      console.log('before')
    },
    // 单个图
    changimg(file) {
      const isLt5M = file.size / 1024 / 1024 <= 5
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!')
      } else {
        let multipleObj = {
          raw: URL.createObjectURL(file.raw),
          uid: file.uid,
          file: file.raw,
          isSuccess: undefined
        }

        this.multipleUrl.push(multipleObj)
      }
    },
    // 删除文件
    multipleRemove(index) {
      this.multipleUrl.splice(index, 1)
    },
    // 点击确认
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.fromData.content.length > 0) {
            this.multipleAdd()
          } else {
            this.$message.error('请先上传文件文件！')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 添加
    async multipleAdd() {
      try {
        let res = await this.request({
          url: '/admin/pictureLiveWorks/batchAdd',
          method: 'post',
          loading: true,
          data: {
            type_id: this.type_id,
            content: JSON.stringify(this.fromData.content),
            user_id: this.fromData.user_id,
            act_id: this.act_id
          }
        })
        if (res) {
          this.$message.success('添加成功')
          this.$router.go(-1)
        }
      } catch (err) {
        this.errorHandler(err)
      }
    },
    // 点击开始上传
    uploadBtn() {
      if (this.is_forever === 0 && !this.copyright_end_time) {
        this.$message.warning('请完善版权信息')
        return
      }

      this.isUpload = false
      this.isPercentage = true
      this.loopUpload(0, this.multipleUrl)

    },
    // 重新上传
    newuploadBtn() {
      if (this.is_forever === 0 && !this.copyright_end_time) {
        this.$message.warning('请完善版权信息')
        return
      }
      this.errorImg = []
      console.log(this.multipleUrl)
      this.loopUpload(0, this.multipleUrl.filter(item => item.isSuccess == 2))
    },
    // 上一个文件上传完毕后上传下一个
    async loopUpload(index, arr) {
      await this.uploadImg(arr[index])
      if (arr.length - 1 > index) {
        this.loopUpload(index + 1, arr)
      }
    },

    //上传文件
    async uploadImg(imgUrl) {
      return new Promise(async (resolve, rej) => {
        try {
          let imgRes = await this.request({
            url: '/uploadsEbook/files',
            method: 'post',
            dataType: 'blob',
            loading: false,
            data: {
              type_id: this.type_id,
              ebook: imgUrl.file,
              is_forever: 1,
              copyright_end_time: '2030-02-01'
            }
          })
          if (imgRes) {
            let fromImgContent = {
              img: imgRes.content.img,
              size: imgRes.content.size,
              width: imgRes.content.width,
              height: imgRes.content.height,
              ratio: imgRes.content.ratio
            }
            this.fromData.content.push(fromImgContent)
            this.percentageNum = parseInt(
              (this.fromData.content.length / this.multipleUrl.length) * 100
            )
            this.multipleUrl.map(item => {
              if (item.uid == imgUrl.uid) {
                item.isSuccess = 1
              }
            })
            resolve()
          }
        } catch (err) {
          this.errorImg.push(imgUrl)
          this.multipleUrl.map(item => {
            if (item.uid == imgUrl.uid) {
              item.isSuccess = 2
            }
          })
          resolve()
          this.errorHandler(err)
        }
      })
    },
    // 点击取消
    cancel() {
      this.$router.go(-1)
    },
    // 获取指定用户列表
    async getPicture(val) {
      if (val !== '') {
        let apiUrl = ''
        let searchList = {}
        // 判断是否指定用户
        if (this.is_appoint == '1') {
          apiUrl = '/admin/pictureLiveAppoint/list'
          searchList = {
            page: 1,
            limit: 9999,
            keywords: val,
            act_id: this.act_id
          }
        } else {
          apiUrl = '/admin/userInfo/list'
          searchList = {
            page: 1,
            limit: 9999,
            keywords: val,
            act_id: this.act_id,
            keywords_type: 5
          }
        }
        try {
          let res = await this.request({
            url: apiUrl,
            method: 'get',
            loading: true,
            data: { ...searchList }
          })
          if (res) {
            this.pictureArr = res.content.data
          }
        } catch (err) {
          this.errorHandler(err)
        }
      } else {
        this.pictureArr = []
      }
    },
    remoteMethod(val) {
      this.getPicture(val)
    }
  }
}
</script>

<style lang="scss" scoped>
.section-title {
  font-weight: 400;
  color: $textColorgreen;
  height: 50px;
  line-height: 50px;
  position: relative;
  padding-left: 20px;
  border-top: 1px solid #ededed;
  border-bottom: 1px solid #ededed;
  font-size: 14px;
  &::before {
    content: "";
    position: absolute;
    width: 2px;
    height: 14px;
    left: 10px;
    top: 0;
    bottom: 0;
    margin: auto;
    background-color: $themeColorponti;
  }
}
.img_ps {
  font-size: 12px;
  font-family: Microsoft YaHei, Microsoft YaHei-Regular;
  font-weight: 400;
  text-align: left;
  color: #727272;
  line-height: 18px;
}
.btn_establish {
  width: 120px;
  height: 40px;
  background: $themeColorponti;
  border-radius: 5px;
  font-size: 16px;
  font-family: MicrosoftYaHei;
  text-align: center;
  color: #ffffff;
  line-height: 40px;
  border: none;
  margin-right: 40px;
}
.btn_shangchuan {
  width: 120px;
  height: 40px;
  background: $themeColorponti;
  border-radius: 5px;
  font-size: 16px;
  font-family: MicrosoftYaHei;
  text-align: center;
  color: #ffffff;
  border: none;
  margin-left: 10px;
}
.shang-box {
  display: flex;
}
.btn_cancel {
  width: 120px;
  height: 40px;
  background: #f2f2f2;
  border-radius: 5px;
  font-size: 16px;
  font-family: MicrosoftYaHei;
  text-align: center;
  color: #000000;
  line-height: 40px;
  border: none;
}
.btn_addBox {
  width: 120px;
  height: 40px;
  border-radius: 5px;
  font-size: 16px;
  font-family: MicrosoftYaHei;
  text-align: center;
  color: #000000;
  border: 1px solid #979797;
}
.upback {
  width: 100px;
  height: 100px;
  background: #fafafa;
  border: 1px dashed #d9d9d9;
  border-radius: 2px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.upimg-maxbox {
  // width: 90%;
  border-bottom: 1px solid #dadada;
  display: grid;
  grid-template-columns: 1fr 1fr;
  .item {
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding: 10px 20px;
    box-sizing: border-box;
    border-bottom: 0.5px solid #eeeeee;
    color: #409eff;
    .right {
      display: flex;
      gap: 10px;
      align-items: center;
      font-size: 12px;
    }
  }
  .color {
    cursor: pointer;
    color: #f56c6c;
  }

  // .upimgmul {
  //   width: 100px;
  //   height: 100px;
  //   background: #fafafa;
  //   border: 1px dashed #d9d9d9;
  //   border-radius: 2px;
  //   display: flex;
  //   flex-direction: column;
  //   align-items: center;
  //   position: relative;
  //   overflow: hidden;
  //   z-index: 1;
  //   margin-right: 10px;
  //   margin-bottom: 5px;
  //   > img {
  //     min-height: 100%;
  //     min-width: 100%;
  //     object-fit: cover;
  //   }
  //   .err-p {
  //     position: absolute;
  //     bottom: 0;
  //     left: 0;
  //     width: 100%;
  //     height: 28px;
  //     line-height: 28px;
  //     background: #f43838;
  //     color: #fff;
  //     text-align: center;
  //   }
  //   .suss-p {
  //     position: absolute;
  //     bottom: 0;
  //     left: 0;
  //     width: 100%;
  //     height: 28px;
  //     line-height: 28px;
  //     background: #0f86f4;
  //     color: #fff;
  //     text-align: center;
  //   }
  // }
  // .upimgmul:hover > div {
  //   position: absolute;
  //   top: 0;
  //   left: 0;
  //   bottom: 0;
  //   right: 0;
  //   width: 100%;
  //   height: 100%;
  //   background: rgba(0, 0, 0, 0.4);
  //   z-index: 9;
  //   display: flex;
  //   flex-direction: row;
  //   align-items: center;
  //   justify-content: center;
  //   > div {
  //     font-size: 18px;
  //     color: #ffffff;
  //   }
  //   > div:first-child {
  //     margin-right: 10px;
  //   }
  // }
}
/deep/.el-upload {
  width: 100%;
  height: 100%;
  flex: 1;
  display: flex;
}
/deep/.el-upload-dragger {
  width: 100%;
  height: unset !important;
  position: relative;
}
.input_nums {
  width: 350px;
}
.caozuo-box {
  width: 90%;
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  .urldata-box {
    font-size: 14px;
    color: #666666;
  }
}
.progressMax {
  display: flex;
  align-items: center;
  .progress-box {
    width: 300px;
    line-height: 30px;
    margin-right: 10px;
  }
}
.upload-boxTwo {
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  overflow: hidden;
  position: relative;
  text-align: center;
  width: 100%;
  height: 100%;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  .center {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 10px;
  }
  img {
    width: 40px;
    height: 40px;
  }
  .btn {
    width: 153px;
    height: 32px;
    background: #00a9b0;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;

    font-size: 14px;
    font-family: Microsoft YaHei, Microsoft YaHei-Regular;
    font-weight: 400;
    color: #ffffff;
  }
  .tip {
    font-size: 12px;
    font-family: MicrosoftYaHei;
    font-weight: normal;
    text-align: center;
    color: #999999;
    line-height: 20px;
  }
}
/deep/.el-upload-dragger {
  border: none;
  // min-height: 100px;
  overflow: inherit;
  height: 100%;
}
.head-maxbox {
  position: relative;
  .head-box {
    width: 30px;
    height: 30px;
    border-radius: 5px;
  }
  .head-p {
    line-height: 30px;
    display: inline-block;
    margin-left: 5px;
    position: absolute;
    top: 0px;
  }
}
/deep/.el-select-dropdown__item {
  margin-bottom: 2px;
}
.block {
  background: #ffffff;
  border-top: 10px solid #f2f2f2;
  border-bottom: 10px solid #f2f2f2;
  padding: 16px 20px;
  box-sizing: border-box;

  .row {
    margin-top: 6px;

    display: flex;
    width: 100%;
    align-items: center;
  }
  .tip {
    font-size: 12px;
    font-family: MicrosoftYaHei;
    font-weight: normal;
    text-align: left;
    color: #f69f39;
  }
  .type {
    font-size: 14px;
    font-family: Microsoft YaHei, Microsoft YaHei-Regular;
    font-weight: 400;
    color: #333333;
    line-height: 18px;
    margin-right: 26px;
  }
  .label {
    font-size: 14px;
    font-family: Microsoft YaHei, Microsoft YaHei-Regular;
    font-weight: 400;
    color: #333333;
    line-height: 18px;
    margin-right: 26px;
  }
  .time {
    margin-left: 50px;
    margin-right: 10px;
    font-size: 12px;
    font-family: MicrosoftYaHei;
    font-weight: normal;
    text-align: left;
    color: #000000;
  }
  .label::before {
    content: "*";
    color: red;
  }
  .time::before {
    content: "*";
    color: red;
  }
}
.innerPage {
  display: flex;
  flex-direction: column;
  .form {
    flex: 1;
    padding: 20px;
    display: flex;
    flex-direction: column;
  }
}
</style>
